/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2011 www.pretty-tools.com
 */

var wwwPrettyTools_NravitsyaMailRuButtonToollbar = {
    TOOLBAR_BUTTON_ID: "NravitsyaMailRu_Button_Pretty_Tools",
    API_URL: "http://connect.mail.ru/share?share_url="
};

wwwPrettyTools_NravitsyaMailRuButtonToollbar.onLoad = function(event)
{
    try
    {
        if (wwwPrettyTools_NravitsyaMailRuButtonConfiguration.isFirstStart())
            this.installButtonOnToolbar();
    }
    catch(ex)
    {
        dump("Exception during onLoad: " + ex + "\n");
    }
}

wwwPrettyTools_NravitsyaMailRuButtonToollbar.installButtonOnToolbar = function ()
{
    try
    {
        var btn = document.getElementById(this.TOOLBAR_BUTTON_ID);
        if (btn) // button exists
            return;

        // let's add it
        var navBar = document.getElementById("nav-bar");
        if (!navBar)
            return;

        var currentSet = navBar.getAttribute("currentset");
        if (!currentSet)
            currentSet = navBar.currentSet;

        var curSet = currentSet.split(",");
        if (curSet.indexOf(this.TOOLBAR_BUTTON_ID) == -1)
        {
            var set = curSet.concat(this.TOOLBAR_BUTTON_ID);
            navBar.setAttribute("currentset", set.join(","));
            document.persist("nav-bar", "currentset");
        }

        navBar.insertItem(this.TOOLBAR_BUTTON_ID);
    }
    catch(ex)
    {
        dump("Exception during installButtonOnToolbar: " + ex + "\n");
    }
}

wwwPrettyTools_NravitsyaMailRuButtonToollbar.onPressButton = function ()
{
    try
    {
        var doc = window.content.document;

        if (!doc || !doc.location || !doc.location.href || !doc.location.href.match(/^http/))
            return;

        var url = this.API_URL + encodeURIComponent(doc.location.href);

        if (!wwwPrettyTools_NravitsyaMailRuButtonConfiguration.isOpenInPopup())
            gBrowser.selectedTab = gBrowser.addTab(url);
        else
        {
            var left = (screen.width / 2) - (300);
            var top = (screen.height / 2) - (200);

            window.open(url, "_blank", "top="+top+",left="+left+",width=600,height=400,resizable=1");
        }
    }
    catch(e)
    {
        dump("Exception during onPressButton: " + e + "\n");
    }
}

try
{
    addEventListener("load", function(event) {
        try {
            wwwPrettyTools_NravitsyaMailRuButtonToollbar.onLoad(event);
        } catch(ex) {
            dump("Exception on inilializing NravitsyaMailRuButtonToollbar.js: " + ex + "\n");
        }
    }, false);
}
catch(ex)
{
    dump("Exception on inilializing NravitsyaMailRuButtonToollbar.js: " + ex + "\n");
}
